package tool

import (
	"log"
	"net/http"
	"strconv"

	"strings"

	"github.com/PuerkitoBio/goquery"
)

func GetAllST(userID int64) {
	res := getPage(userID)
	for k, v := range res {
		AddTask(userID, k, v)
	}
}

func getPage(userID int64) map[string]int {
	url := "http://st.hujiang.com/my/"
	loginUrl := GetUser(userID).Url
	cookies := Login(loginUrl)
	header := &map[string]string{
		"Cookie":       cookies,
		"Content-Type": "application/json",
	}
	resp := Http("GET", url, "", header)
	defer resp.Body.Close()
	// body, err := ioutil.ReadAll(resp.Body)
	// if err != nil {
	// handle error
	// }
	// fmt.Println("resp: ", string(body))
	return ParserHTML(resp)
}

func ParserHTML(resp *http.Response) map[string]int {
	res := make(map[string]int, 0)
	doc, _ := goquery.NewDocumentFromResponse(resp)
	sec := doc.Find(".col-33")
	sec.Each(func(i int, contentSelection *goquery.Selection) {
		// hh, _ := contentSelection.Html()
		// fmt.Println("sec: ", hh)
		title := contentSelection.Find(".title").Text()
		title = strings.TrimSpace(title)
		var s *goquery.Selection
		s = contentSelection.Find(".signed-icon")
		if len(s.Nodes) <= 0 {
			s = contentSelection.Find(".unsigned-icon")
		}
		id := s.AttrOr("data-id", "")
		if id != "" {
			tempID, err := strconv.Atoi(strings.TrimSpace(id))
			if err == nil {
				res[title] = tempID
			} else {
				log.Println("conv st id error: ", err)
			}
		}
	})
	return res
}
